<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/4/3
 * Time: 15:27
 */

namespace app\common\util;


use app\common\exception\CustomerException;

class EncryptUtil
{

    const KEY = "mtc_jBhasoD54fjMa3SsFd7ifjAa";
    const ENCRYPT_METHOD = "AES-256-CBC";

    private static function _format($iv)
    {
        $iv = base64_encode($iv);
        if (strlen($iv) < 16) {
            $iv = str_pad($iv, 16, "0", STR_PAD_RIGHT);
        } else if (strlen($iv) > 16) {
            $iv = substr($iv, 0, 16);
        }
        return $iv;
    }

    public static function encrypt($data, $iv)
    {
        $data = serialize($data);
        $iv = self::_format($iv);
        $encodeData = openssl_encrypt(base64_encode($data), self::ENCRYPT_METHOD, self::KEY, 0, $iv);
        return base64_encode($encodeData);
    }

    public static function decrypt($encrypt, $iv)
    {
        $iv = self::_format($iv);
        $decrypt = openssl_decrypt(base64_decode($encrypt), self::ENCRYPT_METHOD, self::KEY, 0, $iv);
        $decodeData = unserialize(base64_decode($decrypt));
        if ($decodeData) {
            return $decodeData;
        } else {
            throw new CustomerException("数据解密失败");
        }
    }

}